#!/bin/bash
set +e

# 1.fix: runc
runc_v1=$(runc --version | grep 'runc version' | cut -d' ' -f3)
wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache
if [ $? -ne 0 ]; then
    sed -i 's/$releasever/7/g' /etc/yum.repos.d/docker-ce.repo
fi
yum update -y containerd.io

runc_v2=$(runc --version | grep 'runc version' | cut -d' ' -f3)
if [ $runc_v1 != $runc_v2 ]; then
    echo -e "\e[32m\nrunc 升级成功\e[0m"
else
    echo -e "\e[31m\nrunc 已是最新版本，请核对！\e[0m"
fi

# 2.fix: Docker 启用内容信任
if ! grep -q 'export DOCKER_CONTENT_TRUST=1' /etc/profile; then
    echo 'export DOCKER_CONTENT_TRUST=1' >> /etc/profile
    echo -e "\e[32m\n 写入 export DOCKER_CONTENT_TRUST=1\e[0m"
else
    echo -e "\e[31m\n /etc/profile 已包含 'export DOCKER_CONTENT_TRUST=1' 记录\e[0m"
fi
source /etc/profile

# 3.fix: 审核Docker文件和目录
if [ $(cat /etc/audit/audit.rules | grep docker | wc -l) -gt 0 ]; then
    echo -e "\e[31m\n已存在 Docker 相关记录\e[0m"
else
    cat >> /etc/audit/audit.rules <<'EOF'
-w /var/lib/docker -k docker
-w /etc/docker -k docker
-w /usr/lib/systemd/system/docker.service -k docker
-w /usr/lib/systemd/system/docker.socket -k docker
-w /usr/bin/containerd -k docker
-w /usr/bin/runc -k docker
EOF
    echo -e "\e[32m\n/etc/audit/audit.rules 写入 Docker 相关记录\e[0m"
fi

if [ $(cat /etc/audit/rules.d/audit.rules | grep docker | wc -l) -gt 0 ]; then
    echo -e "\e[31m\n已存在 Docker 相关记录\e[0m"
else
    cat >> /etc/audit/rules.d/audit.rules <<'EOF'
-w /var/lib/docker -k docker
-w /etc/docker -k docker
-w /usr/lib/systemd/system/docker.service -k docker
-w /usr/lib/systemd/system/docker.socket -k docker
-w /usr/bin/containerd -k docker
-w /usr/bin/runc -k docker
EOF
    echo -e "\e[32m\n/etc/audit/rules.d/audit.rules 写入 Docker 相关记录\e[0m"
fi

auditctl -R /etc/audit/audit.rules > /dev/null 2>&1
auditctl -R /etc/audit/rules.d/audit.rules > /dev/null 2>&1

auditctl -l | grep 'docker' && service auditd restart
if [ $? -eq 0 ]; then
    echo -e "\e[32m\nauditctl 配置已生效\e[0m"
else
    echo -e "\e[31m\nauditctl 配置未生效\e[0m"
    exit 0
fi

# 4.fix: Docker 日志级别
cat > /etc/docker/daemon.json <<EOF
{
    "exec-opts": ["native.cgroupdriver=systemd"],
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m",
        "max-file": "10"
    },
    "log-level": "info",
    "bip": "169.254.123.1/24",
    "oom-score-adjust": -1000,
    "registry-mirrors": ["https://pqbap4ya.mirror.aliyuncs.com"],
    "storage-driver": "overlay2",
    "storage-opts": ["overlay2.override_kernel_check=true"],
    "live-restore": true
}
EOF

systemctl daemon-reload && systemctl restart docker
if [ $? -eq 0 ]; then
    echo -e "\e[32m\nDocker /etc/docker/daemon.json 已更新配置\n\e[0m"
else
    echo -e "\e[31m\nDocker /etc/docker/daemon.json 已更新配置失败\n\e[0m"
    exit 0
fi
set -e
